package com.gitee.shop.controller;

import com.gitee.shop.domain.*;
import com.gitee.shop.service.OrderService;
import com.gitee.shop.uitl.CommonsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;
import java.util.Set;

@Controller
@RequestMapping("/order")
public class OrderController{
    @Autowired
    private OrderService orderService;
    //生成订单
    @RequestMapping("/create")
    public String create(HttpServletRequest request, Model model){
        //生成订单时必须是登录状态
        //将用户从session中取出
        User user = (User) request.getSession().getAttribute("user");
        if (user == null){
            //没有登录,先登录
            model.addAttribute("error","请先登录再下单！！！");
            return "login";
        }

        //从session中取出购物车
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        //创建订单对象
        Orders order = new Orders();
        order.setOid(CommonsUtils.getUUID());   //设置订单编号
        order.setOrdertime(new Date()); //下单时间
        order.setTotal(cart.getTotal());    //下单金额
        order.setUid(user.getId());
        //设置订单的状态
        order.setState(1);//默认未付款
        //创建订单项
        Map<Integer, CartItem> cartItems = cart.getCartItems();
        for (Map.Entry<Integer, CartItem> entry : cartItems.entrySet()) {

            //创建订单项
            OrderItem orderItem = new OrderItem();
            orderItem.setItemid(CommonsUtils.getUUID());//订单项的id
            orderItem.setCount(entry.getValue().getCount());//设置该项的购买数量
            //购买商品的id
            orderItem.setId(entry.getValue().getItem().getId());
            //设置该项的小计
            orderItem.setSubtotal(entry.getValue().getSubtotal());
            //设置订单的id
            orderItem.setOid(order.getOid());
            //设置商品对象
            orderItem.setItem(entry.getValue().getItem());
            //向订单中添加订单项
            order.getOrderItems().add(orderItem);
        }
        //生成订单
        orderService.creatOrder(order);
        //将订单回显到order页面
        model.addAttribute("order",order);
        return "order";
    }
}

